from google.appengine.api import urlfetch
from xml.dom import minidom
from datetime import datetime
import hashlib
import urllib
from google.appengine.api import users
from datetime import timedelta
from models import UserPrefs

def getPhotoDetails(photoid='0', node=None):
    #infoDoc = getInfoDoc(photoid)
    #exifDoc = getExifDoc(photoid)
    #wita = timedelta(hours=8)
    
    url = ''
    
    if node != None:
        url_s = node.getAttribute('url_s')
        height_s = int(node.getAttribute('height_s'))
        width_s = int(node.getAttribute('width_s'))
        url_m = node.getAttribute('url_m')
        height_m = int(node.getAttribute('height_m'))
        width_m = int(node.getAttribute('width_m'))
        
        if width_s == 240:
            url = url_s
            width = width_s
            height = height_s
        else:
            url = url_m
            width = 240
            height = height_m * 240 / width_m
        
    photoDetails = {
            'id': photoid,
            'secret': node.getAttribute('secret'),
            'server': node.getAttribute('server'),
            'farm': node.getAttribute('farm'),
#            'title': node.getAttribute('title').replace("\n", "<br />"),
#            'description': getText(node.getElementsByTagName("description")[0].childNodes).replace("\n", "<br />"),
#            'ownername': infoDoc.getElementsByTagName("owner")[0].getAttribute('realname') if infoDoc.getElementsByTagName("owner")[0].getAttribute('realname') != "" else infoDoc.getElementsByTagName("owner")[0].getAttribute('username'),
#            'date': (datetime.fromtimestamp(int(infoDoc.getElementsByTagName("dates")[0].getAttribute('posted'))) + wita).strftime("%A, %d %B %Y"),
#            'time': (datetime.fromtimestamp(int(infoDoc.getElementsByTagName("dates")[0].getAttribute('posted'))) + wita).strftime("%I:%M%p"),  
#            'title': getText(infoDoc.getElementsByTagName("title")[0].childNodes).replace("\n", "<br />"),
#            'description': getText(infoDoc.getElementsByTagName("description")[0].childNodes).replace("\n", "<br />"),
#            'tags': getTags(infoDoc),
#            'url': getText(infoDoc.getElementsByTagName("url")[0].childNodes),
#            'localurl': getText(infoDoc.getElementsByTagName("url")[0].childNodes).replace('http://www.flickr.com/', '/'),
#            'nsid': infoDoc.getElementsByTagName("owner")[0].getAttribute('nsid'),
#            'comments': getText(infoDoc.getElementsByTagName("comments")[0].childNodes),
#            'views': infoDoc.getElementsByTagName("photo")[0].getAttribute('views'),
#            'isfavorite': infoDoc.getElementsByTagName("photo")[0].getAttribute('isfavorite'),            
#            'exif': exifData(exifDoc),
#            'location': getLocation(infoDoc),
#            'username': infoDoc.getElementsByTagName("owner")[0].getAttribute('realname') if infoDoc.getElementsByTagName("owner")[0].getAttribute('realname') is not '' else infoDoc.getElementsByTagName("owner")[0].getAttribute('username'),
            'localurl': '/photos/44861801@N07/%s/' % photoid, #dummy nsid
            'src': url,
            'width': width,
            'height': height
    }
    return photoDetails

def getPhotoDetailsJSON(photoid='0'):
    infoDoc = getInfoDoc(photoid)
    exifDoc = getExifDoc(photoid)
    wita = timedelta(hours=8)
            
    photoDetails = {
            'id': photoid,
            'secret': infoDoc.getElementsByTagName("photo")[0].getAttribute('secret'),
            'server': infoDoc.getElementsByTagName("photo")[0].getAttribute('server'),
            'farm': infoDoc.getElementsByTagName("photo")[0].getAttribute('farm'),
            'ownername': infoDoc.getElementsByTagName("owner")[0].getAttribute('realname') if infoDoc.getElementsByTagName("owner")[0].getAttribute('realname') != "" else infoDoc.getElementsByTagName("owner")[0].getAttribute('username'),
            'date': (datetime.fromtimestamp(int(infoDoc.getElementsByTagName("dates")[0].getAttribute('posted'))) + wita).strftime("%d %b %Y"),
            'time': (datetime.fromtimestamp(int(infoDoc.getElementsByTagName("dates")[0].getAttribute('posted'))) + wita).strftime("%I:%M%p"),  
            'title': getText(infoDoc.getElementsByTagName("title")[0].childNodes).replace("\n", "<br />"),
            'description': getText(infoDoc.getElementsByTagName("description")[0].childNodes).replace("\n", "<br />"),
            'tags': getTags(infoDoc),
            'url': getText(infoDoc.getElementsByTagName("url")[0].childNodes),
            'localurl': getText(infoDoc.getElementsByTagName("url")[0].childNodes).replace('http://www.flickr.com/', '/'),
            'nsid': infoDoc.getElementsByTagName("owner")[0].getAttribute('nsid'),
            'comments': getText(infoDoc.getElementsByTagName("comments")[0].childNodes),
            'views': infoDoc.getElementsByTagName("photo")[0].getAttribute('views'),
            'isfavorite': infoDoc.getElementsByTagName("photo")[0].getAttribute('isfavorite'),            
            'exif': exifData(exifDoc),
            'location': getLocation(infoDoc),
            'username': infoDoc.getElementsByTagName("owner")[0].getAttribute('realname') if infoDoc.getElementsByTagName("owner")[0].getAttribute('realname') is not '' else infoDoc.getElementsByTagName("owner")[0].getAttribute('username')
    }
    return photoDetails

def getInfoDoc(photoID):
    user = users.get_current_user()
    if not user:
        infoUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=4ffd08ef36219cd952ccbd153052f833&&photo_id=%s" % photoID
        infoDoc = minidom.parseString(urlfetch.fetch(infoUrl, deadline=60).content)        
        return infoDoc
    
    q = UserPrefs.gql("WHERE user = :1 AND token != NULL", user)
    userprefs = q.get()
    if not userprefs:
        infoUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=4ffd08ef36219cd952ccbd153052f833&&photo_id=%s" % photoID
        infoDoc = minidom.parseString(urlfetch.fetch(infoUrl, deadline=33).content)        
        return infoDoc
    token = userprefs.token
    apiSigString = "c9a1cf81402f8253api_key4ffd08ef36219cd952ccbd153052f833auth_token%smethodflickr.photos.getInfophoto_id%s" % (token, photoID)
    api_sig = hashlib.md5(apiSigString).hexdigest()
    
    params = urllib.urlencode({
        'method': 'flickr.photos.getInfo',
        'api_key': '4ffd08ef36219cd952ccbd153052f833',
        'photo_id': photoID,        
        'auth_token': token,
        'api_sig': api_sig
    })
    infoUrl = "http://api.flickr.com/services/rest/?%s" % params
    infoDoc = minidom.parseString(urlfetch.fetch(infoUrl, deadline=33).content)        
    return infoDoc    

def getExifDoc(photoID):
    exifUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.getExif&api_key=4ffd08ef36219cd952ccbd153052f833&photo_id=%s" % photoID        
    try:
        exifDoc = minidom.parseString(urlfetch.fetch(exifUrl, deadline=33).content)        
    except:
        exifDoc = minidom.parseString("<myxml>Some data</myxml>")
    return exifDoc.getElementsByTagName("exif")

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

def exifData(exif):
    exifString = getExif(exif, 'Model')+ ' + ' + getExif(exif, 'Lens') + '| f/' + getExif(exif, 'FNumber') + getExif(exif, 'ExposureTime')+'Second ISO' + getExif(exif, 'ISO') + getExif(exif, 'FocalLength')
    if len(exifString) > 17:
        return exifString
    return ""

def getExif(nodelist, tag):
    for node in nodelist:
        if node.getAttribute('tag') == tag:
            return getText(node.getElementsByTagName("raw")[0].childNodes) + " "
    return ""

def getTags(doc):
    rc = []
    for node in doc.getElementsByTagName("tag"):
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
        for childNode in node.childNodes:
            if childNode.nodeType == node.TEXT_NODE:
                    rc.append(childNode.data)
            for grandChildNode in childNode.childNodes:                
                if grandChildNode.nodeType == node.TEXT_NODE:
                    rc.append(grandChildNode.data)
    return ' '.join(rc)

def getLocation(doc):
    rc = []
    for node in doc.getElementsByTagName("location"):
        #if node.nodeType == node.TEXT_NODE:
        #    rc.append(node.data)
        for childNode in node.childNodes:
            #if childNode.nodeType == node.TEXT_NODE:
            #        rc.append(childNode.data)
            for grandChildNode in childNode.childNodes:                
                if grandChildNode.nodeType == node.TEXT_NODE:
                    rc.append(grandChildNode.data)    
    rc.reverse()
    return ' > '.join(rc)